package com.takepoints21.mobile;

import java.util.ArrayList;
import java.util.List;

import com.takepoints.android.bo.Item;
import com.takepoints.android.TPConst;
import com.takepoints.android.services.TPServices;
import com.takepoints.android.util.AnimationUtil;
import com.takepoints.android.util.DateUtil;
import com.takepoints.android.util.DownloadImageTask;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;

public class MyOffers extends BaseActivity {
	
	private ListView itemListView = null;
	private ItemListAdapter itemAdapter = null;
	private View footerView = null;
	
	private int nextPage = 1;
	
	private final String IMG_PATH = "https://www.takepoints.com/public/uploads/tmobile/";
	
	public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myitems);
        
        ImageView imgLogo = (ImageView)findViewById(R.id.imgLogo);
        imgLogo.setImageResource(R.drawable.header_my_coupons);
        
        TextView txtHeader = (TextView)findViewById(R.id.txtHeader);
        txtHeader.setText(R.string.title_myoffer);
        manageMenu(2);
        
        ImageView imgAddItem = (ImageView)findViewById(R.id.imgAddItem);
        imgAddItem.setOnClickListener(new View.OnClickListener(){
			 public void onClick(View view) {
				 Intent offerInt = new Intent(view.getContext(), TPOffers.class);
				 startActivityForResult(offerInt, 0);
			 }
        });
        
        itemListView = (ListView)findViewById(R.id.lstItems);
        itemListView.setLayoutAnimation(new AnimationUtil().getSlideDownAnimateCtrl());
        
        footerView = getLayoutInflater().inflate(R.layout.footer_load_more, null);
        TextView txtLoadMore = (TextView)footerView.findViewById(R.id.txtLoadMore);
        txtLoadMore.setOnClickListener(new View.OnClickListener(){
			 public void onClick(View view) {
				 new FetchMyItems(view.getContext()).execute(String.valueOf(nextPage));
			 }
        });
        itemListView.addFooterView(footerView);
        
        itemAdapter = new ItemListAdapter(new ArrayList<Item>());
        itemListView.setAdapter(itemAdapter);
        
        new FetchMyItems(this).execute("1");
	}
	
	private class ItemListAdapter extends BaseAdapter {
		private List<Item> items;
		private LayoutInflater mInflater;

		public ItemListAdapter(List<Item> items){
			mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.items = items;
		}
		
		public void add(Item item){
			items.add(item);
			notifyDataSetChanged();
		}
		
		public void removeAll(){
			items.clear();
			notifyDataSetChanged();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.mycouponrow, null);
			}
			final Item item = items.get(position);
			if(item != null){
				final TableRow tblCard = (TableRow)convertView.findViewById(R.id.tblCard);
				
				ImageView imgCard = (ImageView)convertView.findViewById(R.id.imgCard);
				if(imgCard != null){
					Bitmap bitmap = BitmapFactory.decodeFile(IMG_CACHE_PATH + item.getImageName());
					if(bitmap != null){
						imgCard.setImageBitmap(bitmap);
					} else{
						imgCard.setTag(IMG_PATH + item.getImageName());
						new DownloadImageTask().execute(imgCard);
					}
				}
				
				LinearLayout lnrDetail = (LinearLayout)convertView.findViewById(R.id.lnrDetail);
				lnrDetail.removeAllViews();
				if(lnrDetail != null){
					TextView txtTitle = new TextView(lnrDetail.getContext());
					txtTitle.setText(item.getSiteName());
					txtTitle.setTextSize(12);
					txtTitle.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
					txtTitle.setTextColor(Color.parseColor("#006600"));
					txtTitle.setHeight(LayoutParams.WRAP_CONTENT);
					txtTitle.setPadding(10, 1, 1, 1);
					txtTitle.setSingleLine(false);
					lnrDetail.addView(txtTitle);
					
					TextView txtDesc = new TextView(lnrDetail.getContext());
					txtDesc.setText(item.getItemName());
					txtDesc.setTextSize(11);
					txtDesc.setTextColor(Color.parseColor("#404a4a"));
					txtDesc.setHeight(LayoutParams.WRAP_CONTENT);
					txtDesc.setPadding(9, 1, 1, 1);
					txtDesc.setSingleLine(false);
					lnrDetail.addView(txtDesc);
					
					String dayLeft = null;
					try{
						dayLeft = "เหลืออีก  " + DateUtil.getRemainDate(DateUtil.strToDate(item.getEndDate(), "dd-MMM-yy"));
					} catch(Exception e){
						dayLeft = "ภายในวันที่ " + item.getEndDate();
					}
					TextView txtPointGet = new TextView(lnrDetail.getContext());
					txtPointGet.setText( "ได้  " + item.getOfferPts() + " คะแนน"
							   		   + "   ( " + dayLeft + " )");
					txtPointGet.setTextSize(9);
					txtPointGet.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
					txtPointGet.setTextColor(Color.parseColor("#FF6600"));
					txtPointGet.setPadding(10, 3, 1, 1);
					lnrDetail.addView(txtPointGet);
				}
				
				convertView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 Intent myOfferDetailInt = new Intent(view.getContext(), MyOfferDetail.class);
						 myOfferDetailInt.putExtra("cardId", item.getItemId());
						 myOfferDetailInt.putExtra("siteName", item.getSiteName());
						 startActivityForResult(myOfferDetailInt, 0);
					 }
				});
				convertView.setOnTouchListener(new View.OnTouchListener(){
					 public boolean onTouch(View v, MotionEvent event){
						 int action = event.getAction();
						 switch(action){
						 	case MotionEvent.ACTION_DOWN:
						 		tblCard.setBackgroundColor(Color.LTGRAY);
						 		break;
						 	case MotionEvent.ACTION_UP:
						 		tblCard.setBackgroundResource(R.drawable.bg_my_coupon);
						 		break;
						 	case MotionEvent.ACTION_MOVE:
						 		tblCard.setBackgroundResource(R.drawable.bg_my_coupon);
						 		break;
						 	case MotionEvent.ACTION_CANCEL:
						 		//tblCard.setBackgroundColor(Color.parseColor("#9aa1a0"));
						 		tblCard.setBackgroundResource(R.drawable.bg_my_coupon);
						 		break;
						 	default:
						 		break;
						 }
						 return false;
					}
				 });
			}
			return convertView;
		}

		@Override
		public int getCount() {
			return items.size();
		}

		@Override
		public Object getItem(int position) {
			return items.get(position);
		}

		@Override
		public long getItemId(int position) {
			return items.get(position).hashCode();
		}
	}
	
	class FetchMyItems extends AsyncTask<String, Void, List<Item>>{
    	
		private Context context = null;
		private ProgressDialog progressDlg = null;
		
		FetchMyItems(Context context){
			this.context = context;
		}
		
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            progressDlg = ProgressDialog.show(context, "Takepoints.com", "กำลังโหลด คูปองส่วนลด ...", true);
        }
        
        @Override
        protected List<Item> doInBackground(String... params){
        	final int page = Integer.parseInt(params[0]);
        	List<Item> items = TPServices.getItemList( getSharedIntValue(TPConst.PRF_MEMBER_ID)
													  , TPServices.PROMOTION_TYPE_OFFER
													  , page);
        	return items;
        }
        
        @Override
        protected void onPostExecute(List<Item> result){
        	int rows = (result==null)?0:result.size();
        	if(rows > 0){
	    		try{
	    			for(int i=0; i<rows; i++){
	    				itemAdapter.add(result.get(i));
	    			}
	        		
	    			Item item = result.get(0);
		            ++nextPage;
		            if(nextPage > item.getTotalPage()){
		            	itemListView.removeFooterView(footerView);
		            }
	    		} catch(Exception e){
	    			alert("ผิดพลาด : " + e.getMessage());
	    		}
        	}
        	progressDlg.dismiss();
        }
        
    }
	
}
